package com.cloud.code.牛客网;

import java.util.Stack;

/**
 * 20. 有效的括号
 */
public class Test21 {

    public static void main(String[] args) {

        System.out.println('(' - ')');
        System.out.println('{' - '}');
        System.out.println('[' - ']');

        boolean valid = isValid("]");
        System.out.println(valid);
    }

    //主要是利用栈的先进后出的特性 ，来完成匹配
    public static boolean isValid(String s) {


        Stack<Character> stack = new Stack<>();

        char[] chars = s.toCharArray();
        for (int i = 0; i < chars.length; i++) {
            if (chars[i] == '(' || chars[i] == '{' || chars[i] == '[') {
                stack.push(chars[i]);
            } else {
                if(stack.size() <= 0){
                    return false;
                }
                Character pop = stack.pop();
                if (pop-chars[i] ==-1 || pop-chars[i] ==-2) {
                    continue;
                } else {
                    return false;
                }
            }
        }
        if (stack.size() == 0) {
            return true;
        } else {
            return false;
        }

    }
}
